const axios = require('axios')
const webpack = require('webpack')
const MemoryFs = require('memory-fs')
const path = require('path')
const proxy = require('koa-server-http-proxy')
const ReactSSR = require('react-dom/server')
// const asyncBootstrap = require('react-async-bootstrapper')

// 1.获取index.html文件
// 解决方法直接向client做http请求获取
// 2.启动server/index.js
// 使用webpack启动并编译，储存到缓存中:重新指定编译文件的存储方式
// 3.将访问逻辑与index.html和server-entry结合并返回页面
// 在缓存中读取server-entry文件内容，并使用module._copmon进行解析
// 4.处理资源访问的publicPatch问题
// 使用代理解决返回

const serverConfig = require('../../build/webpack.config.server')
const serverCompiler = webpack(serverConfig)
const mfs = new MemoryFs()
serverCompiler.outputFileSystem = mfs

const Module = module.constructor
let serverBundle, createStoreMap

serverCompiler.watch({}, (err, stats) => {
    if (err) throw err
    stats = stats.toJson()
    stats.errors.forEach(err => console.error('err:', err))
    stats.warnings.forEach(warn => console.warn('warn:', warn))

    const bundlePath = path.join(
        serverConfig.output.path,
        serverConfig.output.filename
    )
    const bundle = mfs.readFileSync(bundlePath, 'utf-8')
    const m = new Module()
    m._compile(bundle, 'server-entry.js')
    serverBundle = m.exports.default
    console.log('serverBundle load success')
    // createStoreMap = m.exports.createStoreMap

})

const getTemplate = () => {
    return new Promise((resolve, reject) => {
        axios.get('http://localhost:3030/public/index.html')
            .then((res) => {
                resolve(res.data)
            })
            .catch(reject)
    })
}

module.exports = function (app) {
    // app.use(staticFiles(path.join(__dirname, '../dist/public')))
    console.log('serverBundle11', serverBundle)
    app.use(proxy('/public', {
        target: 'http://localhost:3030'
    }))
    app.use(async (ctx, next) => {
        await getTemplate().then(template => {
            // const appStore = createStoreMap()
            const context = {}
            const app = serverBundle({}, context, ctx.path)
            const appString = ReactSSR.renderToString(app)

            // asyncBootstrap(app).then(res => {
            if (context.url) {
                ctx.status = 302
                ctx.body = {
                    Location: context.url
                }
                ctx.set({
                    Location: context.url
                })
            } else {
                // console.log('appStore', appStore)
                ctx.response.body = template.replace('<!-- app -->', appString);
            }
            // })

        })
        await next();
    });

}
